package team.hyznrj.studentsys.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import team.hyznrj.studentsys.constant.RedisConstant;
import team.hyznrj.studentsys.entity.account.AccountInfo;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author ReMidDream
 * @date 2018-05-10 13:34
 **/
@Component
public class RedisUtil {

    @Autowired
    private  RedisTemplate<Object, Object> redisTemplate;


    public AccountInfo getAccount(String token){
        AccountInfo accountInfo = (AccountInfo) redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX,token));
        if (accountInfo != null) {
            return accountInfo;
        }
        return  null;
    }

    public void setAccount(String token,AccountInfo account,Integer expire){
        // token作为key 帐号信息作为value
        redisTemplate.opsForValue()
                .set(String.format(RedisConstant.TOKEN_PREFIX,token),
                        account,expire, TimeUnit.SECONDS);
    }


    public void clearAccount(Cookie cookie){
        redisTemplate.opsForValue().getOperations()
                .delete(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
    }

}
